package com.xsedge.xsedge.service.impl;/*
 * @Author ljc
 * @Description //TODO $
 * @Param $
 * @return $
 **/

import com.xsedge.xsedge.dao.*;
import com.xsedge.xsedge.entity.*;
import com.xsedge.xsedge.service.RunDockerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import static com.xsedge.xsedge.tools.SSHTools.sshConnection;
import static java.lang.Integer.valueOf;

@Service
public class RunDockerServiceImp implements RunDockerService {

	@Autowired
	private ContainersRepository containersRepository;

	@Autowired
	private NodeRepository nodeRepository;

	@Autowired
	private ImageRepository imageRepository;

	@Autowired
	private NodeLogRepository nodeLogRepository;

	@Autowired
	private CallFreqRepository callFreqRepository;



	@Override
	public Map<String, Object> runDocker(String ms_name, String node_ip, int container_port) throws IOException {
		Logger log = Logger.getLogger("testLog");
		log.setLevel(Level.ALL);
		log.info(ms_name+node_ip+container_port);
		//先查arch
		NodeInfo nodeInfo = nodeRepository.findNodeByIp(node_ip);
		String node_name = nodeInfo.getnodeName();
		log.info(node_name);
		String arch = nodeInfo.getnodeArch();
		//再查镜像 eg. csbtang/myweb
		Images images =  imageRepository.findImagesByServiceNameAndArch(ms_name,arch);
		String image_name = images.getImageName();
		//docker run -d -p mapping_port:container_port image_name:1.0
		//NodeLog nodeLog = nodeLogRepository.findNodeLogByNodeIp(node_ip);
		//从端口8100开始，统计当前节点的pod数，8100加pod数，即为当前mapping_port
		//int count_pod  = nodeLog.getCount_all_pods();
		Object o = containersRepository.countByNodeIp(node_ip);
		int count_pod  = 0;
		if (o!=null){
			count_pod = Integer.parseInt(o.toString());
		}
		//对外映射端口
		int mapping_port = 8100 + count_pod;
		String cmds = "docker run -d -p "+ mapping_port + ":"+ container_port
				+ " " + image_name +":"+ images.getVersion();
		log.info("执行docker run命令：" + cmds);
		//查找内网穿透的服务器ip和内网穿透的映射port
		String ssh_mapping_ip = nodeInfo.getipMapping();
		int ssh_mapping_port = nodeInfo.getportMapping();
		//sshConnection("101.201.155.125", 6000, "xsedge", false, cmds);
		//ssh 免密登录执行
		String ssh_res = sshConnection(ssh_mapping_ip, ssh_mapping_port, "xsedge", false, cmds);
		String result;
		String containerId;

		if (ssh_res.contains("invalid"))
		{
			result = "error";
			containerId = "failed";
		}else {
			//返回containerId前12位
			String container_id=ssh_res.substring(0,12);
			//插入数据库
			Container container = new Container();
			container.setMappingPort(mapping_port);
			container.setContainerPort(container_port);
			container.setContainerId(container_id);
			container.setServiceName(ms_name);
			container.setImageName(image_name);
			container.setNodeIp(node_ip);
			container.setNodeName(node_name);
			insertContainerLog(container);
			result = "success";
			containerId = container_id;

			CallFreq callFreq = new CallFreq();
			callFreq.setContainerId(container_id);
			callFreq.setCounts(0);
			callFreq.setServiceName(ms_name);
			callFreq.setNodeIp(node_ip);
			callFreq.setNodeName(node_name);
			callFreqRepository.save(callFreq);

		}

		Map<String,Object> map = new HashMap<>();
		map.put("result",result);
		map.put("containerId",containerId);

		return map;
	}

	@Override
	public void insertContainerLog(Container container) {
		containersRepository.save(container);
	}
}